import {Component, OnInit, Output, EventEmitter} from '@angular/core';
import {Observable} from 'rxjs/Observable';
import {BladeContainerBase} from '../../../../shared/blade/blade-container-base';
import {FormBuilder, FormGroup, Validators, FormControl} from '@angular/forms';
import {BladeData} from '../../../../shared/blade/blade-data';
import {Blade} from '../../../../shared/blade/blade.model';
import {Command} from '../../../../shared/toolbar.service';
import {ModelService} from '../../../../service/model.service';
import {Model} from '../../../../entity/model.model';
import {MyValidators} from '../../../../utils/validator/rang';

@Component({
  selector: 'app-model-edit',
  templateUrl: './model-edit.component.html',
  styleUrls: ['./model-edit.component.css']
})
export class ModelEditComponent extends BladeContainerBase<Model> {
  @Output() clearText = new EventEmitter<boolean>();

  constructor(
    private fb: FormBuilder,
    private modelService: ModelService,
    private myValidators: MyValidators,
  ) {
    super(fb);
  }

  ngOnInit() {
    if (!this.isNew) {
      this.commands = [
        new Command('save', '保存', 'fa fa-save', 'setofkey:update', (blade) => this.exeSaveChange(blade), (blade) => this.canSaveChange(blade)),
        new Command('reset', '重置', 'fa fa-save', 'setofkey:reset', (blade) => this.exeReset(blade), (blade) => this.canReset(blade)),
      ]
    }
    else {
      this.currentEntity = new Model(0, 0);
    }
    super.ngOnInit();
  }

  /**
   * 初始化数据
   *
   *
   * @memberof TagEditComponent
   */
  initData(): any | Observable<any> | Promise<any> {

    this.formPatchValue(this.currentEntity);


  }

  exeSaveChange(blade: any): void {
    this.saveChange();
  }

  canSaveChange(blade: any): boolean {
    return this.hasChange() && !this.hasError();
  }

  exeReset(blade: any): void {
    return this.formGroup.reset(this.currentEntity);
  }

  canReset(blade: any): boolean {
    return this.hasChange();
  }

  createForm() {
    let obj: {} = {
      'modelName': [this.currentEntity.modelName, [
        Validators.required,
        Validators.maxLength(20),
      ], (control: FormControl): any => this.modelNameAsnyValidator(control)],
      'deviceCategoryId': [this.currentEntity.deviceCategoryId],
      'factoryId': [this.currentEntity.factoryId],
      'capaCity': [this.currentEntity.capaCity, [
        Validators.pattern('^[0-9]+(.[0-9]{0,2})?$'),
        Validators.maxLength(20),
      ]],

    };
    this.formGroup = this.fromBuider.group(obj);
  }

  /**
   * 设置表单错误对象
   *
   *
   * @memberof BladeContainerBase
   */
  setFormError(): void {
    this.formErrors = {
      'modelName': '',
      'capaCity': '',
    };
  }

  canCreate() {
    return !this.formGroup.value.deviceCategoryId || !this.formGroup.valid;
  }

  /**
   * 设置表单验证信息
   *
   *
   * @memberof BladeContainerBase
   */
  setValidationMessages(): void {
    this.validationMessages = {
      'modelName': {
        'required': '型号名称不能为空。',
        'maxlength': '型号名称不能多于20个字符长度。',
        'exist': '型号名称已存在'
      },
      'capaCity': {
        'pattern': '装机容量必须数字组成。',
        'maxlength': '装机容量不能多于20个字符长度。',
      },


    };
  }

  modelNameAsnyValidator(control: FormControl) {
    if (!control.value || control.value == this.currentEntity.modelName) {
      return Observable.of(null);
    }
    return this.modelService.hasModelName(control.value, this.currentEntity.modelId)
      .map(res => res ? {exist: true} : null);
  }

  /**
   * 创建一个测点信息
   *
   *
   * @memberof TurbstatusEditComponent
   */
  onCreate() {
    if (!this.hasError()) {
      this.changeCurrent();
      this.modelService.create(this.currentEntity)
        .then(res => {
          if (res) {
            let parentContainerInstance = this.parentBlade.bladeContainerInstance;
            parentContainerInstance.refresh(res);
            this.bladeService.closeBlade(this.currentBlade);
          } else {
            throw new Error('数据新增失败！')
          }
        })
        .catch(error => this.bladeData.error = error)
        .then(res => this.bladeData.isLoading = false);
    }
  }

  /**
   *
   *
   *
   * @memberof TagsEditComponent
   */
  saveChange(): any | Promise<any> | Observable<any> {

    if (this.canSaveChange(this.currentBlade)) {
      this.changeCurrent()
      return this.modelService.update(this.currentEntity)
        .then(res => {

          if (res) {
            this.clearText.emit(true);
            (this.parentBlade.bladeContainerInstance).refresh(res);
            this.bladeService.closeBlade(this.currentBlade);
            return true;
          }
          throw new Error('数据更新失败！')

        })
        .catch(error => this.bladeData.error = error)
        .then(res => this.bladeData.isLoading = false);
    }
  }

  changeCurrent() {
    this.bladeData.isLoading = true;
    let formValue = this.formGroup.value;

    this.currentEntity.modelName = formValue.modelName;
    this.currentEntity.factoryId = formValue.factoryId;
    this.currentEntity.capaCity = formValue.capaCity;
    this.currentEntity.deviceCategoryId = formValue.deviceCategoryId;
  }


}


// WEBPACK FOOTER //
// ./src/app/module/basic/model/model-edit/model-edit.component.ts
